

part of appcommon;

class ProcessMaskWidget extends StatefulWidget {
  const ProcessMaskWidget({this.width, this.height, required this.controller});
  final double? width;
  final double? height;
  final ProcessMaskController controller;
  @override
  createState() => _ProcessMaskWidgetState(width: width, height: height);
}

class _ProcessMaskWidgetState extends State<ProcessMaskWidget> {
  _ProcessMaskWidgetState({this.height, this.width});
  double? width;
  double? height;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (width == null || height == null) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        var size = MediaQuery.of(context).size;
        width = size.width;
        height = size.height;
        setState(() {});
      });
    }
    widget.controller._setState(setState);
  }

  @override
  void dispose(){
    super.dispose();
    widget.controller._setState(null);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    if (width == null || height == null) {
      return const SizedBox();
    }

    var h = (widget.controller._percent / 100) * height!;

    return Offstage(
      offstage: widget.controller._isOffstage,
      child: Container(
          color: Colors.transparent,
          width: width,
          height: height,
          child: Stack(
              children: [
                if (width != null && height != null)
                  Positioned(bottom: h, left: 0, right: 0, top: 0, child: Container(
                    width: width,
                    height: height,
                    color: Colors.black.withOpacity(0.4)
                  )),
                Center(
                  child: Text("${widget.controller._percent}%", style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.w400,
                      color: Colors.orange
                  )),
                ),
              ]
          )
      )
    );
  }
}


class ProcessMaskController {
  ProcessMaskController([bool? offStage]): _isOffstage = offStage ?? true;
  int _percent = 0;
  bool _isOffstage;
  bool _isFailure = false;
  bool _isUploading = false;
  void Function(void Function())? _updateState;
  void _setState(void Function(void Function())? setState){
    _updateState = setState;
  }

  void _onProcessChange(int current, int amount){
    _percent = (current / amount * 100).toInt();
    _update();
  }

  void _show(){
    _percent = 0;
    _isOffstage = false;
    _isUploading = true;
    _isFailure = false;
    _update();
  }

  void _hide(){
    _isUploading = false;
    _isOffstage = true;
    _update();
  }

  void _failure(){
    _isUploading = false;
    _isFailure = true;
    _percent = 0;
  }

  void _update(){
    _updateState?.call(() { });
  }
}